package com.asman.worker.splash;

import android.app.Activity;
import android.app.Dialog;
import android.widget.ImageView;

import com.asman.base.lib.glide.GlideApp;
import com.asman.worker.R;

import java.lang.ref.WeakReference;

/**
 * SplashScreen

 * 启动屏
 * from：http://www.devio.org
 * Author:CrazyCodeBoy
 * GitHub:https://github.com/crazycodeboy
 * Email:crazycodeboy@gmail.com
 */
public class SplashScreen {
    private static Dialog mSplashDialog;
    private static WeakReference<Activity> mActivity;

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity, final int themeResId) {
        if (activity == null) return;
        mActivity = new WeakReference<>(activity);
        activity.runOnUiThread(() -> {
            if (!activity.isFinishing()) {
                mSplashDialog = new Dialog(activity, themeResId);
                mSplashDialog.setContentView(R.layout.activity_splash);
                mSplashDialog.setCancelable(false);
                GlideApp.with(activity).load(R.drawable.img_splash).into((ImageView) mSplashDialog.findViewById(R.id.iv_bg));
                if (!mSplashDialog.isShowing()) {
                    mSplashDialog.show();
                }
            }
        });
    }

    /**
     * 打开启动屏
     */
    public static void show(final Activity activity) {
        show(activity, R.style.SplashScreen_Fullscreen);
    }

    /**
     * 关闭启动屏
     */
    public static void hide(Activity activity) {
        if (activity == null) {
            if (mActivity == null) {
                return;
            }
            activity = mActivity.get();
        }

        if (activity == null) return;

        final Activity _activity = activity;

        _activity.runOnUiThread(() -> {
            if (mSplashDialog != null && mSplashDialog.isShowing()) {
                boolean isDestroyed = _activity.isDestroyed();
                if (!_activity.isFinishing() && !isDestroyed) {
                    mSplashDialog.dismiss();
                }
                mSplashDialog = null;
            }
        });
    }
}
